package com.mulanweb.handler;

import com.mulanweb.api.module.model.wechat.ErrorCode;
import com.mulanweb.db.common.WxErrorCode;
import com.mulanweb.db.common.WxParaFormatter;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/10.
 */
public class PostHandler {


    public static Map<String,String> post(String url,String content, String type){
        CloseableHttpClient client = null;
        CloseableHttpResponse resp = null;
        try{
           type = type == null || type.length()<=0 ? "application/json" : type ;
            client = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            post.addHeader("Content-type",type);
            StringEntity entity = new StringEntity(content, ContentType.create(type, "UTF-8"));
            post.setEntity(entity);
            resp = client.execute(post);
            int statusCode = resp.getStatusLine().getStatusCode();
            if(statusCode>=200&&statusCode<300) {
                String str = EntityUtils.toString(resp.getEntity(),"utf-8");
                Map<String,String> para ;
                if(type.indexOf("json")>-1){
                    para=WxParaFormatter.jsonToMap(str);
                }else{
                    para=WxParaFormatter.xmlToMap(str);
                }
                if(para.containsKey("errcode")
                        &&  !("0".equals(para.get("errcode")))){
                    para.put("errorCN",WxErrorCode.ERRORCODE.get(Integer.parseInt(para.get("errcode"))).toString());
                    System.out.println(para.get("errorCN"));
                }
                return para;
            }else{
                //TODO 请求错误
                /*String str = EntityUtils.toString(resp.getEntity(),"utf-8");
                System.out.println(str);*/
                return null;
            }
        }catch (Exception ioe){
            ioe.printStackTrace();
            return null ;
        }finally {
            try{
                client.close();
                resp.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    public static Map<String,String> post(String url){
        return post(url,"",null);
    }
}
